import { AnyAction, Reducer } from 'redux';
import { EffectsCommandMap } from 'dva';
import { message } from 'antd';
import router from 'umi/router';

import {
  querySendAPackageList,
  saveVipUser,
} from './service';
import { fetchValidation } from '@/utils';

export type Effect = (
  action: AnyAction,
  effects: EffectsCommandMap & { select: <T>(func: (state: {}) => T) => T },
) => void;

export interface ModelType {
  namespace: string;
  state: {};
  effects: {
    fetch: Effect;
    save: Effect;
  };
  reducers: {
    save: Reducer;
  };
}

const Model: ModelType = {
  namespace: 'SendAPackageImport',

  state: {
    dataInfo: {
      list: [],
      count: 0,
    },
  },

  effects: {
    * fetch({ payload }, { call, put }) {
      const response = yield call(querySendAPackageList, payload);
      const data = fetchValidation(response);
      yield data && put({
        type: 'save',
        payload: response.body,
      });
    },

    * save({ payload }, { call, put }) {
      const formData = new FormData();
      Object.entries(payload).map((item: any) => (
        formData.append(item[0], item[1])
      ));
      const response = yield call((saveVipUser), { body: formData });
      if (!response) {
        return;
      }
      const data = fetchValidation(response);
      if (data) {
        message.success('添加成功!');
        router.goBack();
      }
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        dataInfo: action.payload,
      };
    },
  },
};

export default Model;
